package com.interview.score.controller;

import com.interview.score.common.Result;
import com.interview.score.common.ResultMessage;
import com.interview.score.common.StatusCode;

import com.interview.score.service.DataExchangeService;
import com.interview.score.service.ExamRoomService;
import com.interview.score.utils.RedisKeyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/supervisor")
@Tag(name = "考场管理员接口",description = "实现考场内管理功能")
public class SupervisorController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Environment environment;
    @Autowired
    private ExamRoomService examRoomService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DataExchangeService dataExchangeService;
    @Autowired
    private RedisKeyUtils redisKeyUtils;

    //设置考场号
    @Operation(summary = "设置考场号", description = "格式为面试考生组号+考场号：B2" )
    @PostMapping("/setExamRoomId")
    public Result setExamRoomId(@RequestParam String examRoomId) {
        //校验输入参数规则
        boolean success=examRoomService.checkInputExamRoomIdRule(examRoomId);
        if (success) {
            //过滤字母
            String examRoomId_letter = examRoomId.replaceAll("\\s*", "").replaceAll("[^(A-Z)]", "");
            //校验组号是否存在
            boolean exist_groupId = dataExchangeService.checkGroupIdExists(examRoomId_letter);
            //过滤数字
            String examRoomId_number = examRoomId.replaceAll("\\s*", "").replaceAll("[^(0-9)]", "");
            boolean exist_examRoomCode = dataExchangeService.checkExamRoomCodeExist(examRoomId_number);

            if (exist_examRoomCode&&exist_groupId){
                //设置考场ID
                redisTemplate.opsForValue().setIfAbsent(environment.getProperty("ExamRoomIdKey"), examRoomId);
                return new Result(true, StatusCode.OK, ResultMessage.OPERATION_SUCCESS,null);
            }else {
                return new Result(false, StatusCode.ERROR, ResultMessage.EXAMROOMID_ERROR,null);

            }
        }else{
            return new Result(false, StatusCode.ERROR, ResultMessage.EXAMROOMID_ERROR,null);
        }

    }

    //获取考场号
    @Operation(summary = "获取考场号", description = "获取考场号")
    @PostMapping("getExamRoomId")
    public Result getExamRoomId() {
        String examRoomId = examRoomService.getExamRoomId();
        return new Result(true, StatusCode.OK, ResultMessage.OPERATION_SUCCESS,examRoomId);
    }

    //获取考场考生抽签信息
    @Operation(summary = "获取考场内考生的抽签信息",description = "获取考场内考生的抽签信息")
    @PostMapping("getExameeDrawLotsSummary")
    public Result getExameeDrawLotsSummary(){
        //获取考场号，确认考场号存在
        String examRoomId = examRoomService.getExamRoomId();
        if (examRoomId==null||examRoomId.isEmpty()){

            return new Result(false, StatusCode.ERROR, ResultMessage.EXAMROOMID_NotSet,null);
        }
        Set absentSequence = examRoomService.getAbsentSequence();
        String totalExameeAmount = examRoomService.getTotalExameeAmount();
        if (absentSequence==null||totalExameeAmount==""||totalExameeAmount==null){
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put(environment.getProperty("AbsentSequenceKey"),"考生缺考数据尚未下载，请点击下载按钮下载");
            hashMap.put(environment.getProperty("TotalExameeAmountKey"),"考生人数数据尚未下载，请点击下载按钮下载");
            return new Result(false,StatusCode.ERROR,ResultMessage.Not_DownLoad_Yet,null);
        }else {
            String absentSequenceString = absentSequence.toString();
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put(environment.getProperty("AbsentSequenceKey"),absentSequenceString);
            hashMap.put(environment.getProperty("TotalExameeAmountKey"),totalExameeAmount);
            return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,hashMap);
        }
    }

    @Operation(summary = "获取本考场内考官的抽签信息",description = "获取本考场内考官的抽签信息")
    @PostMapping("getExaminerDrawLotsInfo")
    public Result getExaminerDrawLotsInfo(){
        //获取考场号，确认考场号存在
        String examRoomId = examRoomService.getExamRoomId();
        if (examRoomId==null||examRoomId.isEmpty()){
            return new Result(false, StatusCode.ERROR, ResultMessage.EXAMROOMID_NotSet,null);
        }
        /**
         * 查询数据库中考官Id是否存在
         */
        //1、组装ID
        String examinerIdNumbersInRedis = environment.getProperty("ExaminerIdNumbersKey") + "-" + examRoomId;
        Set members = redisTemplate.opsForSet().members(examinerIdNumbersInRedis);
        if (members==null||members.isEmpty()){
            return new Result(false, StatusCode.ERROR, ResultMessage.ExaminerInfo_Not_DownLoad_Yet,null);
        }
        //2、获取考官数据
        Iterator iterator = members.iterator();
        ArrayList<Map> result = new ArrayList<>();
        while (iterator.hasNext()){
            String idNumber = (String) iterator.next();
            String examinerDetailsKey = environment.getProperty("ExaminerDetailsKey") + "-" + examRoomId+"-"+idNumber;
            Map entries = redisTemplate.opsForHash().entries(examinerDetailsKey);
            entries.put(environment.getProperty("IdNumberField"),idNumber.substring(6,14));
            result.add(entries);
        }

        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,result);
    }

    @Operation(summary = "获取本考场内评分要素",description = "获取本考场内评分要素")
    @PostMapping("getScoreElementDetails")
    public Result getScoreElementDetails() {
        String examRoomId = examRoomService.getExamRoomId();
        //获取Id集合
        String scoreElementIdsKey = redisKeyUtils.spliceTwoRedisKey("ScoreElementIdsKey", examRoomId);
        Set members = redisTemplate.opsForSet().members(scoreElementIdsKey);
        if (members==null||members.isEmpty()){
            return new Result(false, StatusCode.ERROR, ResultMessage.QUERY_FAIL,null);
        }
        Iterator iterator = members.iterator();
        ArrayList<Map> result = new ArrayList<>();
        while (iterator.hasNext()){
            String id = (String) iterator.next();
            String scoreElementDetailsKey = redisKeyUtils.spliceThreeRedisKey("ScoreElementDetailsKey", examRoomId, id);
            Map entries = redisTemplate.opsForHash().entries(scoreElementDetailsKey);
            entries.put(environment.getProperty("IdHash"),id);
            result.add(entries);
        }
        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,result);
    }

    @Operation(summary = "设定全局考试时间",description = "设定全局考试时间,时间为分钟的整数")
    @PostMapping("setExamTime")
    public Result setExamTime(@RequestParam("minute")String minute){
        String s = examRoomService.setExamTime(minute);
        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,s);
    }

    @Operation(summary = "获取全局考试时间",description = "获取全局考试时间")
    @PostMapping("getExamTime")
    public Result getExamTime(){
        String examTime = examRoomService.getExamTime();
        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,examTime);
    }


}
